<template>
    <div>

        <el-form :inline="true">

            <el-form-item label="标题">
                <el-input v-model="title" placeholder=""></el-input>
            </el-form-item>

            <el-form-item label="申请单号">
                <el-input v-model="applicationNum" placeholder=""></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-select v-model="status" clearable placeholder="请选择">
                    <el-option label="草稿" value="1"></el-option>
                    <el-option label="审核中" value="2"></el-option>
                    <el-option label="驳回" value="3"></el-option>
                    <el-option label="已办结" value="4"></el-option>
                </el-select>
            </el-form-item>

            <el-button type="primary" @click="fetchData()">查询</el-button>
        </el-form>
        <el-button type="primary" @click="goToAddPage()">新增</el-button>


        <el-table :data="tableData" border style="width: 100%">
            <el-table-column fixed label="序号" align="center" width="50" type="index" :index="indexMethod">
            </el-table-column>
            <el-table-column fixed prop="status" label="状态" align="center" width="90" :formatter="formatStatus">
            </el-table-column>
            <el-table-column prop="applicationDate" align="center" label="申请日期" width="160" :formatter="dataFormat">
            </el-table-column>
            <el-table-column prop="applicationNum" align="center" label="申请单号" width="150">
            </el-table-column>
            <el-table-column prop="title" align="center" label="标题" width="150">
            </el-table-column>
            <el-table-column prop="applicationPerson" align="center" label="申请人" width="150">
            </el-table-column>
            <el-table-column prop="lenderPerson" align="center" label="出借人" width="150">
            </el-table-column>
            <el-table-column prop="borrowDate" align="center" label="借用日期" width="160" :formatter="dataFormat">
            </el-table-column>
            <el-table-column prop="planReturnDate" align="center" label="计划归还日期日期" width="160" :formatter="dataFormat">
            </el-table-column>
            <el-table-column prop="borrowReason" align="center" label="申请事由" width="200">
            </el-table-column>
            <el-table-column prop="assetDetail" align="center" label="退库资产明细" width="150">
                <template slot-scope="scope">
                    <el-button @click="assetDetailList(scope.row.applicationNum)" type="text"
                        size="small">查看明细</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="creatorPerson" align="center" label="创建人" width="150">
            </el-table-column>
            <el-table-column prop="created" align="center" label="创建时间" width="180" :formatter="dataFormat">
            </el-table-column>
            <el-table-column fixed="right" align="center" label="操作" width="100">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="goToEditPage(scope.row.applicationNum,
                        scope.row.title, scope.row.applicationDate, scope.row.applicationPerson,
                        scope.row.borrowDate, scope.row.borrowReason, scope.row.planReturnDate,
                        scope.row.lenderPerson
                    )">修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页-->
        <el-pagination @size-change="sizeData" @current-change="pageData" :page-sizes="[1, 5, 10, 20, 30, 60]"
            :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="count">
        </el-pagination>

        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
            <el-form :inline="true">

                <el-form-item label="资产编码">
                    <el-input v-model="number" placeholder=""></el-input>
                </el-form-item>

                <el-form-item label="资产名称">
                    <el-input v-model="name" placeholder=""></el-input>
                </el-form-item>

                <el-form-item label="资产类型">
                    <el-select v-model="assetCategoryId" clearable placeholder="请选择资产类型">
                        <el-option v-for="type in assetTypeList" :key="type.id" :label="type.name" :value="type.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="存放位置">
                    <el-select v-model="locationId" clearable placeholder="请选择存放位置">
                        <el-option v-for="location in locationList" :key="location.id" :label="location.name"
                            :value="location.id" />
                    </el-select>
                </el-form-item>

                <el-button type="primary" @click="fetchAssetDetailData()">查询</el-button>
                <el-button type="primary" @click="detailFlash()">重置</el-button>
            </el-form>
            <el-table :data="assetDetailData" border>
                <el-table-column type="selection" width="45" align="center"></el-table-column>
                <el-table-column label="序号" align="center" width="40" type="index" :index="indexMethod">
                </el-table-column>
                <el-table-column prop="number" label="资产编码" align="center" width="120">
                </el-table-column>
                <el-table-column prop="assetName" align="center" label="资产名称" width="130">
                </el-table-column>
                <el-table-column prop="model" align="center" label="规格型号" width="120">
                </el-table-column>
                <el-table-column prop="assetCategoryName" align="center" label="资产分类" width="120">
                </el-table-column>
                <el-table-column prop="unit" align="center" label="单位" width="100">
                </el-table-column>
                <el-table-column prop="adminName" align="center" label="管理人" width="100">
                </el-table-column>
                <el-table-column prop="nowStorageLocationName" align="center" label="存放位置">
                </el-table-column>
            </el-table>

            <el-pagination @size-change="sizeAssetDetailData" @current-change="pageAssetDetailData"
                :page-sizes="[1, 5, 10, 20, 50]" :page-size="assetDetailLimit"
                layout="total, sizes, prev, pager, next, jumper" :total="assetDetailCount">
            </el-pagination>

            <div style="text-align: center; margin-top: 30px;">
                <el-button @click="handleConfirm" type="primary">确定</el-button>
                <div style="display: inline-block; width: 30px;"></div> <!-- 添加间隔 -->
                <el-button @click="dialogFormVisible = false">取消</el-button>
            </div>
        </el-dialog>
    </div>

</template>


<script>
import assetBorrowApi from "@/api/asset-borrow";
import { assetCategory } from "@/api/assetCategory";
import storageLocationApi from "@/api/location";
import moment from 'moment';

export default {
    data() {
        return {
            tableData: [],
            page: 1,
            limit: 10,
            count: 0,
            title: '',
            applicationNum: '',
            status: '',

            dialogFormVisible: false, // 控制弹窗的显示和隐藏
            assetDetailData: [], // 初始化资产明细数据
            assetDetailPage: 1, // 弹窗当前页
            assetDetailLimit: 10, //弹窗每页显示条数
            assetDetailCount: 0, //弹窗数据总数
            name: '',
            number: '',
            assetCategoryId: '',
            locationId: '',
            dialogTitle: '',
            assetTypeList: [],  //资产详情类型
            locationList: []    //资产详情位置
        }
    },

    created() {
        this.fetchData()
    },

    methods: {
        //查询存放类型列表
        getAssetTypeList() {
            assetCategory.findAll().then(response => {
                this.assetTypeList = response.data
            })
        },

        //查询存放位置列表
        getLocationList() {
            storageLocationApi.findAll().then(response => {
                this.locationList = response.data
            })
        },

        goToAddPage() {
            this.$router.push({ name: 'borrowAddPage' }); // 跳转到 add 页面
        },

        goToEditPage(applicationNum, title, applicationDate, applicationPerson, borrowDate, borrowReason, planReturnDate,lenderPerson) {
            this.$router.push({
                name: 'borrowAddPage', query: {
                    applicationNum, title, applicationDate, applicationPerson, borrowDate
                    , borrowReason, planReturnDate,lenderPerson
                }
            }); // 跳转到 add 页面，并携带申请单号
        },

        fetchData() {
            assetBorrowApi.list({
                page: this.page,
                limit: this.limit,
                title: this.title,
                applicationNum: this.applicationNum,
                status: this.status
            }).then(response => {
                this.tableData = response.data;  // 确保 response 有 data 属性
                this.count = response.count;  //总页数
            }).catch(error => {
                console.error("获取数据失败:", error);  // 捕获和打印错误
            });
        },


        //资产明细
        assetDetailList(applicationNum) {
            this.applicationNum = applicationNum;

            // 设置动态标题
            this.dialogTitle = `单号${this.applicationNum}的资产详情`;

            // 打开弹窗
            this.dialogFormVisible = true;

            //查询条件（位置和类型）
            this.getAssetTypeList();
            this.getLocationList();

            // 请求资产明细数据
            this.fetchAssetDetailData();
        },

        fetchAssetDetailData() {
            assetBorrowApi.assetList({
                applicationNum: this.applicationNum,
                page: this.assetDetailPage, // 使用当前页码
                limit: this.assetDetailLimit, // 使用每页条数
                name: this.name,
                number: this.number,
                model: this.model,
                assetCategoryId: this.assetCategoryId,
                locationId: this.locationId
            }).then(response => {
                this.assetDetailData = response.data; // 资产明细数据
                this.assetDetailCount = response.count; // 总数
            }).catch(error => {
                console.error("获取资产明细失败:", error);
                this.$message.error("获取资产明细失败，请重试。");
            });
        },


        sizeData(size) {
            this.limit = size
            this.fetchData()
        },
        pageData(page) {
            this.page = page
            this.fetchData()
        },

        // 资产明细分页大小变化
        sizeAssetDetailData(size) {
            this.assetDetailLimit = size; // 更新分页大小
            this.assetDetailPage = 1; // 重置为第一页
            this.fetchAssetDetailData(); // 请求新的数据
        },

        // 资产明细页码变化
        pageAssetDetailData(page) {
            this.assetDetailPage = page; // 更新当前页
            this.fetchAssetDetailData(); // 请求新的数据
        },
        detailFlash() {
            this.number = '';
            this.name = '';
        },



        //增加一个格式化日期的方法
        dataFormat(row, column) {

            let date = row[column.property]

            if (date == undefined) {
                return ''
            }

            return moment(date).format('YYYY-MM-DD hh:mm:ss')
        },

        indexMethod(index) {
            return index + 1;
        },

        handleClick(row) {
            console.log(row);
        },

        handleConfirm() {
            // 获取选中的行数据
            const selectedRows = this.$refs.assetDetailTable.selection;

            // 处理选中的数据
            if (selectedRows.length > 0) {
                // 例如，打印选中的数据或进行其他操作
                console.log('选中的资产明细数据:', selectedRows);

                // 这里可以添加您需要的提交逻辑，比如 API 请求
                // assetBorrowApi.submitData(selectedRows).then(response => {
                //     // 处理成功和失败
                // }).catch(error => {
                //     console.error("提交失败:", error);
                // });
            } else {
                this.$message.warning("请至少选择一项数据！");
            }

            // 关闭弹窗
            //this.dialogFormVisible = false;
        },

        //将状态从数字显示为对应的值
        formatStatus(row) {
            switch (String(row.status)) {
                case '1':
                    return '草稿';
                case '2':
                    return '审核中';
                case '3':
                    return '驳回';
                case '4':
                    return '已办结';
                default:
                    return '待处理';
            }
        }
    }
}
</script>